package com.joysuch.wwyt.edu.controller;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import cn.zlg.common.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.bean.PageParam;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateVo;
import com.joysuch.wwyt.edu.entity.WwytEduCertificate;
import com.joysuch.wwyt.edu.entity.WwytEduCertificateUser;
import com.joysuch.wwyt.edu.service.WwytEduCertificateService;
import com.joysuch.wwyt.edu.service.WwytEduCertificateUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author : pp
 * @date : Created in 2021/4/14 20:34
 */
@RestController
@RequestMapping("/edu/cartificate/v2")
@Api(tags = "证书-证书种类管理")
public class WwytEduCertificateController {

    @Autowired
    private WwytEduCertificateService certificateService;
    @Autowired
    private BaseTypeGroupItemDao itemDao;
    @Autowired
    private WwytEduCertificateUserService wwytEduCertificateUserService;

    @RequiresPermissions("edu:cartificate:v2:add")
    @PostMapping("add")
    @ApiOperation("证书种类添加")
    public ResultBean add(@Valid @RequestBody WwytEduCertificate entity) {
        certificateService.add(entity);
        return ResultBean.success("添加证书种类成功");
    }

    //    @RequiresPermissions("edu:cartificate:v2:page")
    @PostMapping("page")
    @ApiOperation("证书种类分页查询")
    public ResultBean page(@Valid @RequestBody PageParam pageParam) {
        Page page = (Page) certificateService.page(new Page<>(pageParam.getPageNum() + 1, pageParam.getPageSize())
                , new QueryWrapper<WwytEduCertificate>().lambda().likeRight(WwytEduCertificate::getOrgCode, Context.getCompanyCode()).eq(WwytEduCertificate::getTenentId, Context.getCurrentTenantId()).eq(WwytEduCertificate::getDeleteFlag,'0').orderBy(true, false, WwytEduCertificate::getUpdateTime));
        Object collect = page.getRecords();
        //处理字典表名称
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            collect = page.getRecords().stream().map(e -> {
                WwytEduCertificate certificate = (WwytEduCertificate) e;
                Long certTypeId = certificate.getCertTypeId();
                WwytEduCertificateVo vo = new WwytEduCertificateVo();
                if (certTypeId != null) {
                    Optional<BaseTypeGroupItem> byId = itemDao.findById(certTypeId);
                    if (byId.isPresent()) {
                        BaseTypeGroupItem baseTypeGroupItem = byId.get();
                        BeanUtils.copyProperties(e, vo);
                        vo.setCertificatTypeName(baseTypeGroupItem.getName());
                        return vo;
                    } else {
                        BeanUtils.copyProperties(e, vo);
                        return vo;
                    }
                } else {
                    BeanUtils.copyProperties(e, vo);
                    return vo;
                }
            }).collect(Collectors.toList());
        }
        return ResultBean.pageData((List) collect, page.getTotal());
    }

//    @PostMapping("findAll")
//    @ApiOperation("查询所有证书")
//    public ResultBean findAll(){
//        List<WwytEduCertificate> list = certificateService.list(new QueryWrapper<WwytEduCertificate>().lambda()
//                .eq(WwytEduCertificate::getTenentId, Context.getCurrentTenantId())
//                .eq(WwytEduCertificate::getOrgCode, Context.getCompanyCode()));
//        return ResultBean.success(list);
//    }

    @RequiresPermissions("edu:cartificate:v2:delete")
    @PostMapping("delete")
    @ApiOperation("批量删除")
    public ResultBean delete(@NotEmpty(message = "请勾选删除项") @RequestBody List<Long> idList) {
        //todo check used
        checkUsed(idList);
        certificateService.removeByIds(idList);
        return ResultBean.success("删除成功");
    }

    private void checkUsed(List<Long> idList) {
        List<WwytEduCertificateUser> certificateUsers = wwytEduCertificateUserService.selectByCertIds(idList);
        if (CollectionUtils.isNotEmpty(certificateUsers)) {
            throw new IllegalArgumentException("所选删除项存在被持证管理使用!请先解除使用再删除!");
        }

    }

    //    @RequiresPermissions("edu:cartificate:v2:getOne")
    @GetMapping("getOne")
    @ApiOperation("证书种类查询单条")
    public ResultBean getOne(@NotNull(message = "证书种类id不能为空") Long id) {
        WwytEduCertificate byId = certificateService.getById(id);
        return ResultBean.success(byId);
    }

    @RequiresPermissions("edu:cartificate:v2:update")
    @PostMapping("update")
    @ApiOperation("证书种类更新")
    public ResultBean updateOne(@Valid @RequestBody WwytEduCertificate entity) {
        if (entity.getId() == null) {
            throw new IllegalArgumentException("证书种类id不能为空");
        }
        entity.setUpdateTime(new Date());
        certificateService.update(entity);
        return ResultBean.success("更新成功");
    }

    @GetMapping("getUsed")
    @ApiOperation("查询启用状态证书")
    public ResultBean getUsed() {
        List<WwytEduCertificate> list = certificateService.list(new QueryWrapper<WwytEduCertificate>().lambda()
                .eq(WwytEduCertificate::getUseState, 1)
                .eq(WwytEduCertificate::getTenentId, Context.getCurrentTenantId())
                .likeRight(WwytEduCertificate::getOrgCode, Context.getCompanyCode()).eq(WwytEduCertificate::getDeleteFlag,'0'));
        return ResultBean.success(list);
    }
}
